package com.efuture.redis.findprovicedemo.dao.impl;

import com.efuture.redis.findprovicedemo.dao.ProviceDao;
import com.efuture.redis.findprovicedemo.domian.Provice;
import com.efuture.redis.findprovicedemo.utils.JdbcUtils;
import com.efuture.redis.findprovicedemo.utils.JedisPoolUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import redis.clients.jedis.Jedis;

import java.util.List;

/**
 * @author ：赵山山
 * @description：TODO
 * @date ：2021/10/5 11:52 下午
 */
public class ProviceDaoImpl implements ProviceDao {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());

    @Override
    public List<Provice> findAllProvice() {
        //查找数据库
        String sql = "select * from provice";
        List<Provice> provices = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Provice>(Provice.class));
        return provices;




    }

    @Override
    public String  findAllProviceForRedis() {
        //从redis查 如果redis有数据 直接用redis数据 否则用数据库数据
        Jedis jedis = JedisPoolUtils.getJedis();
        String provice = jedis.get("provice");
        if(null==provice||provice.trim().length()<1){
            //没有数据 从数据库里面找
            System.out.println("从数据库获取数据");
            String sql = "select * from provice";
            List<Provice> provices = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Provice>(Provice.class));
            //将数据存到redis种
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                provice =  objectMapper.writeValueAsString(provices);
                jedis.set("provice",provice);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("从redis获取数据");
        }
        jedis.close();
        return provice;
    }
}

